package com.influxdb.demo.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Query;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class InfluxdbUtils {
    private String userName;
    private String password;
    private String url;
    public String database;
    private String retentionPolicy;

    private InfluxDB influxDB;
    public static String policyNamePix = "logmonitor";

    public InfluxdbUtils(String influxDBUrl, String userName, String password, String database) {
        this.url = influxDBUrl;
        this.userName = userName;
        this.password = password;
        this.database = database;
    }

    public InfluxDB getInfluxDB() {
        if (this.influxDB == null) {
            influxDB = influxDbBuild();
        }
        return influxDB;
    }

    private InfluxDB influxDbBuild() {
        if (influxDB == null) {
            influxDB = InfluxDBFactory.connect(url, userName, password);
        }
        try {
            createDB(database);
            influxDB.setDatabase(database);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            influxDB.setRetentionPolicy(retentionPolicy);
        }
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }

    /****
     *  创建数据库
     * @param database
     */
    private void createDB(String database) {
        influxDB.query(new Query("CREATE DATABASE " + database));
    }
}
